package com.apisix.service.client;

import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.http.*;
import org.springframework.web.client.RestTemplate;

import java.security.MessageDigest;
import java.util.Map;

/**
 * 用于测试获取JWT令牌的客户端测试类
 * 此类可以独立运行，用于测试TokenController
 */
public class TokenClientTest {

    private static final String APP_ID = "AAAAAkey";
    private static final String APP_SECRET = "BBBBBSecret";
    private static final String TOKEN_URL = "http://localhost:8080/api/token";

    public static void main(String[] args) {
        try {
            // 生成当前时间戳
            String timestamp = String.valueOf(System.currentTimeMillis());
            
            // 计算授权签名（app_secret+时间戳的MD5哈希值）
            String authorization = getMD5Hash(APP_SECRET + timestamp);
            
            System.out.println("使用的参数:");
            System.out.println("APP_ID: " + APP_ID);
            System.out.println("APP_SECRET: " + APP_SECRET);
            System.out.println("时间戳: " + timestamp);
            System.out.println("计算的Authorization值: " + authorization);
            System.out.println("");

            // 创建HTTP请求头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            headers.set("Authorization", authorization);
            headers.set("Accesskey", APP_ID);

            // 创建HTTP请求
            HttpEntity<Void> requestEntity = new HttpEntity<>(headers);

            // 构建URL，包含时间戳参数
            String url = TOKEN_URL + "?t=" + timestamp;
            
            // 发送请求
            RestTemplate restTemplate = new RestTemplateBuilder().build();
            ResponseEntity<Map> response = restTemplate.exchange(
                    url,
                    HttpMethod.GET,
                    requestEntity,
                    Map.class
            );

            // 输出响应结果
            System.out.println("状态码: " + response.getStatusCode());
            System.out.println("响应体: " + response.getBody());

            // 获取令牌和过期时间
            if (response.getBody() != null) {
                String token = (String) response.getBody().get("token");
                Integer expiresIn = (Integer) response.getBody().get("expires_in");

                System.out.println("\n获取的JWT令牌: " + token);
                System.out.println("令牌有效期(秒): " + expiresIn);
            }

        } catch (Exception e) {
            System.err.println("获取令牌失败: " + e.getMessage());
            e.printStackTrace();
        }
    }

    /**
     * 计算字符串的MD5哈希值（大写）
     */
    private static String getMD5Hash(String input) throws Exception {
        MessageDigest md = MessageDigest.getInstance("MD5");
        byte[] hashBytes = md.digest(input.getBytes("UTF-8"));
        
        StringBuilder sb = new StringBuilder();
        for (byte b : hashBytes) {
            sb.append(String.format("%02X", b));
        }
        
        return sb.toString();
    }
} 